import Vue from 'vue'
import Vuex from 'vuex'

import {
  SET_USER,
  SET_IS_AUTHENTICATED,
  CHANGE,
  CURRENT_SELECT_MENU,
  DEFAULT_OPEN_MENU
} from './Mutatuins-Types'

Vue.use(Vuex)

const state = {
  collapsed: false,  //控制菜单的展开与折叠
  user: {}, //保存用户信息
  isAuthenticated: false, //保存是否认证状态，默认是没有认证
  currentSelectedMenu: JSON.parse(window.localStorage.getItem('currentSelectedMenu')) || ['/index/home'],//保存当前被选中的菜单选项的key，默认是首页
  defaultOpenMenu: JSON.parse(window.localStorage.getItem('defaultOpenMenu')) || []//保存当前被选中的展开项，默认是不选中
}
const mutations = {
  [CHANGE] (state) {
    state.collapsed = !state.collapsed
  },
  [CURRENT_SELECT_MENU] (state, payload) {
    //state.currentSelectedMenu = [payload]
    if (payload) {
      window.localStorage.setItem('currentSelectedMenu', JSON.stringify(payload))
    } else {
      state.currentSelectedMenu = ['/index/home']
    }

  },
  [DEFAULT_OPEN_MENU] (state, payload) {
    if (payload) {
      let newArr = []
      let newString = ''
      payload.map(item => {
        let splitItem = item.split('/')
        console.log(splitItem)

        newString = '/' + splitItem[1] + '/' + splitItem[2]
        newArr.push(newString)
        console.log(newArr)

      })
      window.localStorage.setItem('defaultOpenMenu', JSON.stringify(newArr))
    } else {
      state.defaultOpenMenu = []
    }

  },
  [SET_USER] (state, user) {
    if (user) {
      state.user = user
      //window.localStorage.setItem('userInfo', user)
    } else {
      state.user = {}
    }
  },
  [SET_IS_AUTHENTICATED] (state, isAuthenticated) {
    if (isAuthenticated) {
      state.isAuthenticated = isAuthenticated
    } else {
      state.isAuthenticated = false
    }
  }
}
const actions = {
  setUser: ({ commit }, user) => {
    commit(SET_USER, user)
  },
  setIsAuthenticated: ({ commit }, isAuthenticated) => {
    commit(SET_IS_AUTHENTICATED, isAuthenticated)
  },
  clearCurrentState: ({ commit }) => {
    commit(SET_IS_AUTHENTICATED, false)
    commit(SET_USER, null)
    commit(CURRENT_SELECT_MENU, false)
    commit(DEFAULT_OPEN_MENU, false)
  }
}
const getters = {
  user: state => state.user,
  isAuthenticated: state => state.isAuthenticated
}

export default new Vuex.Store({
  state,
  actions,
  mutations,
  getters
})
